package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import utils.JarReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {
    /** 定义socket监听的端口号 */
    private int port = 8080;

    /** jar包的存放路径 */
    private final String JAR_PATH = "F:\\lagouproject\\2-1\\Minicat\\source\\webapps";

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载解析相关的配置，web.xml
        loadServlet();

        // 加载webapps路径下
        loadJarServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    /**
     * 加载解析webapps路径下的jar包中的web.xml,初始化Servlet
     */
    private void loadJarServlet() {
        System.out.println("获取webapps文件下的jar");
        File file = new File(JAR_PATH);
        String[] filelist = file.list();
        for (int i = 0; i < filelist.length; i++) {
            System.out.println(JAR_PATH + "\\" + filelist[i]);
            InputStream inputStream = JarReader.readFromJar(JAR_PATH + "\\" + filelist[i], "web.xml");
            doAnalysizeWebXml(inputStream, JAR_PATH + "\\" + filelist[i]);
        }

    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        doAnalysizeWebXml(resourceAsStream,"");
    }

    private void doAnalysizeWebXml(InputStream inputStream, String jarPath) {
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                if (jarPath != null && !"".equals(jarPath)) {
                    // 从jar包中获取class
                    URL url = new URL("file:" + jarPath);
                    URLClassLoader myClassLoader1 = new URLClassLoader(new URL[] { url }, Thread.currentThread() .getContextClassLoader());
                    Class<?> myClass1 = myClassLoader1.loadClass(servletClass);
                    servletMap.put(urlPattern, (HttpServlet) myClass1.newInstance());
                } else {
                    servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
